"""
root_dir/
	book_list.htm
	books/
		book_1/
			novel_index.htm
			number0_99999.htm
			pics/
				0_99999.jpg
		book_2/
		book_3/
		...


"""

import os
import re
import shutil


origin_path = '../website/'
target_path = '../books/'

def start():
	os.mkdir(target_path)
	book_list = open(target_path + 'pre_book_list.htm', 'w')
	for book_number in xrange(0, 2020):
		print book_number
		book_path = '{}novel{}.htm'.format(origin_path, book_number)
		if os.path.exists(book_path):
			with open(book_path, 'r') as f:
				book_index_content = f.read()
			book_name = re.findall("<div id=\"title\">(.*?)</div>", book_index_content)[0]
			book_list.write('<a href=\"book_{}/novel_index.htm\">{} {}</a><br />'.format(book_number, book_number, book_name))

			book_dir_path = '{}book_{}/'.format(target_path, book_number)
			if not os.path.exists(book_dir_path):
				os.mkdir(book_dir_path)
			with open('{}/novel_index.htm'.format(book_dir_path), 'w') as f:
				f.write(book_index_content)
			target_image_path = '{}images/'.format(book_dir_path)
			if not os.path.exists(target_image_path):
				os.mkdir(target_image_path)
			for subpage in re.findall('\d+.htm', book_index_content):
				subpage_path = '{}{}'.format(origin_path, subpage)
				if os.path.exists(subpage_path):
					with open(subpage_path, 'r') as f:
						subpage_content = f.read()
					for image in re.findall("http://.*?\d+.jpg", subpage_content):
						image_id = re.findall('\d+.jpg', image)[0]
						subpage_content = subpage_content.replace(image, 'images/{}'.format(image_id))
						origin_image_path = '{}pics/{}'.format(origin_path, image_id)
						try:
							shutil.copy(origin_image_path, target_image_path)
						except:
							pass
					with open("{}{}".format(book_dir_path, subpage), 'w') as f:
						f.write(subpage_content)

	book_list.close()
			
	
if __name__ == '__main__':
	#try:
	#	shutil.rmtree(target_path)
	#except:
	#	pass
	start()